﻿using Microsoft.Extensions.DependencyInjection;
using RSDesktop.ViewModels;
using RSDesktop.Views.Popup;
using RSFrame.Services;
using RSModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace RSDesktop.Views
{
    /// <summary>
    /// WorkWindow.xaml 的交互逻辑
    /// </summary>
    public partial class WorkWindow : Window
    {
        public WorkWindow(Workspace currentWorkspace)
        {
            InitializeComponent();
            ServiceCollection serviceDescriptors = new();
            serviceDescriptors.RegisterRequiredServices();
            var sp = serviceDescriptors.BuildServiceProvider();
            RSEventService = sp.GetRequiredService<IRSEventService>();
            DataContext = new WorkWindowViewModel(currentWorkspace, sp.GetRequiredService<ICompanyService>(), sp.GetRequiredService<ICarService>());
            CurrentWorkspace = currentWorkspace;
            PositionMap.Source = new Uri("file:///" + Environment.CurrentDirectory + @"\Assets\Pages\position\index.html");
            PathMap.Source = new Uri("file:///" + Environment.CurrentDirectory + @"\Assets\Pages\path\path.html");
            carTimeline.ItemsSource = MessageList;
            gauge.ItemsSource = CurrentLoadPercent;
            dataList.ItemsSource = DataMonitors;
        }

        public IRSEventService RSEventService { get; set; }

        public ObservableCollection<RSEvent> MessageList { get; private set; } = new();

        public ObservableCollection<CurrentLoadPercent> CurrentLoadPercent { get; } = new() { new CurrentLoadPercent() { Number = 0f } };

        public List<RSEvent> EventsBuffer { get; set; } = new();

        public List<Position> Positions { get; set; }

        public ObservableCollection<DataMonitor> DataMonitors { get; set; } = new()
        {
            new DataMonitor()
            {
                Title = "PM2.5",
                Details = "郑州市PM2.5监测",
                WarningValue = 10,
                UseWarning = true,
                HttpAddress = "http://service.envicloud.cn:8082/v2/cityairlive/BXNUB3NOYWLUMTYZMDE0NJMZNZQZOQ==/101180101",
                DataPath = "PM25",
            },
            new DataMonitor()
            {
                Title = "SO2",
                Details = "郑州市SO2浓度监测",
                WarningValue = 100,
                UseWarning = true,
                HttpAddress = "http://service.envicloud.cn:8082/v2/cityairlive/BXNUB3NOYWLUMTYZMDE0NJMZNZQZOQ==/101180101",
                DataPath = "SO2",
            },
            new DataMonitor()
            {
                Title = "NO2",
                Details = "郑州市NO2监测",
                UseWarning = false,
                HttpAddress = "http://service.envicloud.cn:8082/v2/cityairlive/BXNUB3NOYWLUMTYZMDE0NJMZNZQZOQ==/101180101",
                DataPath = "NO2",
            },
            new DataMonitor()
            {

            },
        };

        public Workspace CurrentWorkspace { get; set; }

        public int CurrentMonitoringCarID { get; set; }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            new UserInfo(CurrentWorkspace).Show();
        }

        private void SearchBox_KeyDown(object sender, KeyEventArgs e)
        {
            var textBox = (TextBox)sender;
            if (e.Key == Key.Enter)
                SearchButton.Command.Execute(textBox.Text);
        }

        private void SearchCarBox_KeyDown(object sender, KeyEventArgs e)
        {
            var textBox = (TextBox)sender;
            if (e.Key == Key.Enter)
                SearchCarButton.Command.Execute(textBox.Text);
        }

        private void ResultList_SelectionChanged(object sender, RoutedEventArgs e)
        {
            if ((sender as ListBox).SelectedItem != null)
            {
                var item = ((ListBox)sender).SelectedItem as Car;
                CarLicBox.Text = item.License;
                CurrentMonitoringCarID = item.ID;
                MessageList.Clear();
                CurrentLoadPercent[0].Number = 0;
            }
            else
            {
                CarLicBox.Clear();
                CarDriverBox.Clear();
            }
        }

        private void GetMessage_Button_Click(object sender, RoutedEventArgs e)
        {
            //new MobileSimulation(EventsBuffer, Positions, PositionMap).Show();
            List<RSEvent> temp = RSEventService.GetRSEventsByCarID(CurrentMonitoringCarID);
            if (temp != null)
            {
                MessageList.Clear();
                MessageList.AddRange(temp);
                if (MessageList.Count > 0)
                {
                    CarDriverBox.Text = MessageList[0].DriverID.ToString();
                    CurrentLoadPercent[0].Number = MessageList[0].CurrentLoad * 100f / (ResultList.SelectedItem as Car).LoadCapacity;
                    PathMap.ExecuteScriptAsync($"setMarker({MessageList[0].Lng},{MessageList[0].Lat})");
                }
            }
        }

        private void Clear_Button_Click(object sender, RoutedEventArgs e)
        {
            MessageList.Clear();
        }

        private void GeneratePath_Button_Click(object sender, RoutedEventArgs e)
        {
            if (MessageList.Count > 0)
            {
                var temp = MessageList.Reverse();
                StringBuilder coordinates = new("[");
                foreach (var item in temp)
                {
                    coordinates.Append($"[{item.Lng},{item.Lat}],");
                }
                coordinates.Append(']');
                PathMap.ExecuteScriptAsync($"displayRout({coordinates})");
            }
        }

        private void Warning_Button(object sender, RoutedEventArgs e)
        {
            (sender as Button).Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#dddddd"));
        }

        private void StartButton_Click(object sender, RoutedEventArgs e)
        {
            if (dataList.SelectedItem is DataMonitor d)
                d.Start();
        }

        private void StopButton_Click(object sender, RoutedEventArgs e)
        {
            if (dataList.SelectedItem is DataMonitor d)
                d.Stop();
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            DataMonitors.Add(new DataMonitor());
            dataList.SelectedItem = DataMonitors.Last();
        }

        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            if (dataList.SelectedItem is DataMonitor d)
                DataMonitors.Remove(d);
        }

        private void DataList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((sender as ListBox).SelectedItem is DataMonitor d)
            {
                ConfigViwer.DataContext = d;

            }
        }
    }

}